#! /usr/bin/env python
# -*- coding: utf-8 -*-

### BEGIN LICENSE
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin Ltd
#
# Author:     Kobe Lee <xiangli@ubuntukylin.com>
# Maintainer: Ubuntu Kylin
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
### END LICENSE

import os
import httplib
# import gtk
from gi.repository import Gtk, Gdk
import platform
import time

HOME = os.path.expandvars('$HOME')

VERSION = '2.1.3'

province_list = [
    '北京',
    '上海',
    '天津',
    '重庆',
    '黑龙江',
    '吉林',
    '辽宁',
    '内蒙古',
    '河北',
    '山西',
    '陕西',
    '山东',
    '新疆',
    '西藏',
    '青海',
    '甘肃',
    '宁夏',
    '河南',
    '江苏',
    '湖北',
    '浙江',
    '安徽',
    '福建',
    '江西',
    '湖南',
    '贵州',
    '四川',
    '广东',
    '云南',
    '广西',
    '海南',
    '香港',
    '澳门',
    '台湾'
]

weather_encode_table = {
            '00':'晴',
            '01':'多云',
            '02':'阴',
            '03':'阵雨',
            '04':'雷阵雨',
            '05':'雷阵雨伴有冰雹',
            '06':'雨夹雪',
            '07':'小雨',
            '08':'中雨',
            '09':'大雨',
            '10':'暴雨',
            '11':'大暴雨',
            '12':'特大暴雨',
            '13':'阵雪',
            '14':'小雪',
            '15':'中雪',
            '16':'大雪',
            '17':'暴雪',
            '18':'雾',
            '19':'冻雨',
            '20':'沙尘暴',
            '21':'小到中雨',
            '22':'中到大雨',
            '23':'大到暴雨',
            '24':'暴雨到大暴雨',
            '25':'大暴雨到特大暴雨',
            '26':'小到中雪',
            '27':'中到大雪',
            '28':'大到暴雪',
            '29':'浮尘',
            '30':'扬沙',
            '31':'强沙尘暴',
            '53':'霾',
            '99':'无'
        }
wind_direction_encode_table = {
            '0':'无持续风向',
            '1':'东北风',
            '2':'东风',
            '3':'东南风',
            '4':'南风',
            '5':'西南风',
            '6':'西风',
            '7':'西北风',
            '8':'北风',
            '9':'旋转风'
        }

wind_power_encode_table = {
    '0':'微风',
    '1':'3-4 级',
    '2':'4-5 级',
    '3':'5-6 级',
    '4':'6-7 级',
    '5':'7-8 级',
    '6':'8-9 级',
    '7':'9-10 级',
    '8':'10-11 级',
    '9':'11-12 级'
}

weather_icons={
            'd0.gif':'weather-clear',
            'd1.gif':'weather-few-clouds',
            'd2.gif':'weather-overcast',
            'd3.gif':'weather-showers-scattered',
            'd4.gif':'weather-storm',
            'd5.gif':'weather-storm',
            'd6.gif':'weather-snow',
            'd7.gif':'weather-showers-scattered',
            'd8.gif':'weather-showers-scattered',
            'd9.gif':'weather-showers',
            'd10.gif':'weather-showers',
            'd11.gif':'weather-showers',
            'd12.gif':'weather-severe-alert',
            'd13.gif':'weather-snow',
            'd14.gif':'weather-snow',
            'd15.gif':'weather-snow',
            'd16.gif':'weather-snow',
            'd17.gif':'weather-snow',
            'd18.gif':'weather-fog',
            'd19.gif':'weather-snow',
            'd20.gif':'weather-fog',
            'd21.gif':'weather-showers-scattered',
            'd22.gif':'weather-showers-scattered',
            'd23.gif':'weather-showers',
            'd24.gif':'weather-showers',
            'd25.gif':'weather-showers',
            'd26.gif':'weather-snow',
            'd27.gif':'weather-snow',
            'd28.gif':'weather-snow',
            'd29.gif':'weather-fog',
            'd30.gif':'weather-fog',
            'd31.gif':'weather-fog',
            'd53.gif':'weather-fog',
            'n0.gif':'weather-clear-night',
            'n1.gif':'weather-few-clouds-night',
            'n2.gif':'weather-overcast',
            'n3.gif':'weather-showers-scattered',
            'n4.gif':'weather-storm',
            'n5.gif':'weather-storm',
            'n6.gif':'weather-snow',
            'n7.gif':'weather-showers-scattered',
            'n8.gif':'weather-showers-scattered',
            'n9.gif':'weather-showers',
            'n10.gif':'weather-showers',
            'n11.gif':'weather-showers',
            'n12.gif':'weather-severe-alert',
            'n13.gif':'weather-snow',
            'n14.gif':'weather-snow',
            'n15.gif':'weather-snow',
            'n16.gif':'weather-snow',
            'n17.gif':'weather-snow',
            'n18.gif':'weather-fog',
            'n19.gif':'weather-snow',
            'n20.gif':'weather-fog',
            'n21.gif':'weather-showers-scattered',
            'n22.gif':'weather-showers-scattered',
            'n23.gif':'weather-showers',
            'n24.gif':'weather-showers',
            'n25.gif':'weather-showers',
            'n26.gif':'weather-snow',
            'n27.gif':'weather-snow',
            'n28.gif':'weather-snow',
            'n29.gif':'weather-fog',
            'n30.gif':'weather-fog',
            'n31.gif':'weather-fog',
            'n53.gif':'weather-fog'
        }

# class ObserveStat(object):
#     def __init__(self,id,city,ptime,time,WD,WS,SD,weather,img1,img2,temp,temp1,temp2):
#         self.id = id
#         self.city = city
#         self.ptime = ptime
#         self.time = time
#         self.WD = WD
#         self.WS = WS
#         self.SD = SD
#         self.weather = weather
#         self.img1 = img1
#         self.img2 = img2
#         self.temp = temp
#         self.temp1 = temp1
#         self.temp2 = temp2

def get_parent_path(folderpath, level=1):
    parent_path = os.path.realpath(folderpath)
    while(level > 0):
        parent_path = os.path.dirname(parent_path)
        level -= 1
    return parent_path

def get_http_time():
    try:
        conn = httplib.HTTPConnection("www.beijing-time.org")
        conn.request("GET", "/time.asp")
        response = conn.getresponse()
        if response.status == 200:
            result = response.read()
            data = result.split("\r\n")
            # print data#['t0=new Date().getTime();', 'nyear=2014;', 'nmonth=5;', 'nday=7;', 'nwday=3;', 'nhrs=13;', 'nmin=32;', 'nsec=2;']
            year = data[1][len("nyear")+1 : len(data[1])-1]
            month = data[2][len("nmonth")+1 : len(data[2])-1]
            day = data[3][len("nday")+1 : len(data[3])-1]
            # hrs = data[5][len("nhrs")+1 : len(data[5])-1]
            # bjtime = "%s-%s-%s %s hour" % (year, month, day, hrs)
            bjtime = "%s年%s月%s日" % (year, month, day)
            return bjtime
    except:
        return "0000年00月00日"


def searchNic():
    nicPath = "/sys/class/net"
    flagUp = False
    if not os.path.exists(nicPath):
        print "%s doesn't exists." % str(nicPath)
        return False
    for list in os.listdir(nicPath):
        file_path = os.path.join(nicPath, list) + "/operstate"
        if os.path.exists(file_path) and os.path.isfile(file_path):
            fp = open(file_path, 'r')
            all_text = fp.read()
            if "up" in all_text:
                flagUp = True
            fp.close()
    if flagUp:
        return True
    else:
        return False

class project_path_not_found(Exception):
    """Raised when we can't find the project directory."""

def get_data_file(*path_segments):
    """Get the full path to a data file.

    Returns the path to a file underneath the data directory (as defined by
    `get_data_path`). Equivalent to os.path.join(get_data_path(),
    *path_segments).
    """
    return os.path.join(get_data_path(), *path_segments)


def get_data_path():
    """Retrieve indicator-china-weather data path

    This path is by default <indicator_china_weather_lib_path>/../data/ in trunk
    and /usr/share/indicator-china-weather in an installed version but this path
    is specified at installation time.
    """

    # Get pathname absolute or relative.
    path = os.path.join(
        os.path.dirname(__file__), "../")
    # print os.path.join(os.path.abspath(os.path.curdir))

    abs_data_path = os.path.abspath(path)
    if not os.path.exists(abs_data_path):
        raise project_path_not_found
    return abs_data_path

def get_builder(builder_file_name):
    """Return a fully-instantiated gtk.Builder instance from specified ui
    file

    :param builder_file_name: The name of the builder file, without extension.
        Assumed to be in the 'ui' directory under the data path.
    """
    # Look for the ui file that describes the user interface.
    ui_filename = get_data_file('ui', '%s.ui' % (builder_file_name))
    if not os.path.exists(ui_filename):
        ui_filename = None
    builder = Gtk.Builder()
    builder.add_from_file(ui_filename)
    return builder

def get_local_date():
    # local_date = time.strftime("%Y年%m月%d日", time.localtime(time.time()))
    cur_date = time.localtime(time.time())
    year = time.strftime("%Y",cur_date)
    month = time.strftime("%m",cur_date)
    if month[0:1] == '0':
        month = month[1:2]
    day = time.strftime("%d",cur_date)
    if day[0:1] == '0':
        day = day[1:2]
    local_date = "%s年%s月%s日" % (year, month, day)
    return local_date

# def get_local_format_time():
#     '''
#     year-month-day hour:minute:second
#     2014-05-07 13:51:30
#     '''
#     local_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
#     return local_date

# def get_local_normal_time():
#     '''
#     year month day hour minute
#     201405071351
#     '''
#     local_date = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
#     return local_date


def get_parent_path(folderpath, level=1):
    parent_path = os.path.realpath(folderpath)
    while(level > 0):
        parent_path = os.path.dirname(parent_path)
        level -= 1
    return parent_path


def get_distro_info():
    ufpath = '/etc/ubuntukylin-release'
    if(os.path.exists(ufpath) and os.path.isfile(ufpath)):
        uf = open(ufpath)
        lines = uf.readlines()
        rtn = []
        for line in lines:
            kv = line.split('=')
            if (kv[0] == 'DISTRIB_ID'):
                v = kv[1]
                rtn.append(v[:-1])
            if (kv[0] == 'DISTRIB_RELEASE'):
                v = kv[1]
                rtn.append(v[:-1])
        uf.close()
        return rtn
    else:
        dist = platform.dist()
        distname = dist[0]
        distversion = dist[1]
        return [distname, distversion]

# def get_machine_id():
#     fpath = '/var/lib/dbus/machine-id'
#     if(os.path.exists(fpath) and os.path.isfile(fpath)):
#         f = open(fpath, 'r')
#         id = f.read()
#         f.close()
#         id = id.replace('\n','')
#         if(id == ''):
#             return 'unknown'
#         else:
#             return id
#     else:
#         return 'unknown'

# # indicator-china-weather version
# def get_weather_version():
#     return VERSION

def get_last_time():
    time_text = None
    usrPath = os.path.join(HOME, '.config/ubuntukylin/indicator-china-weather/pingback.time')
    if os.path.exists(usrPath):
        fp = open(usrPath)
        try:
            time_text = fp.read( ).replace('\n', '')
        finally:
            fp.close()
    return time_text

def set_last_time(time_text):
    abs_path = os.path.join(HOME, '.config/ubuntukylin/indicator-china-weather')
    if not os.path.isdir(abs_path):
        os.makedirs(abs_path)
    usrPath = os.path.join(abs_path, 'pingback.time')
    fp = open(usrPath, 'w')
    fp.write(time_text)
    fp.close()

def handle_drag(window, event):
    if event.button == 1:
       #if event.type == gtk.gdk._2BUTTON_PRESS:#an event is double click
       if int(event.type) in (5, 6):#GDK_2BUTTON_PRESS GDK_3BUTTON_PRESS
           pass
       else:
           window.begin_move_drag(event.button, event.x_root, event.y_root, event.time)
    return False

def handle_move(widget, event):
    if event.x <= 0:
        event.x=0
        widget.move(event.x, event.y)
    return True

def add_drag_support(window):
    window.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
    window.connect("button-press-event", handle_drag)
